package com.zxjbyte.yiyi.framework.quartz.util;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import com.zxjbyte.yiyi.framework.common.exception.ServiceException;
import com.zxjbyte.yiyi.framework.common.util.ClassXUtils;
import com.zxjbyte.yiyi.framework.quartz.handler.IJobHandler;

/**
 * @Author zhangxingjia
 * @Date 2024/1/4 16:26
 * @Version: 1.0
 */
public class JobUtil {

    /**
     * 检测处理器是否合法
     *
     * @param jobHandler
     */
    public static String checkJobHandler(String jobHandler){
        if(StrUtil.contains(jobHandler, StringPool.DOT)){
            try {
                Class.forName(jobHandler);
            } catch (ClassNotFoundException e) {
                throw new ServiceException("目标任务处理器类["+ jobHandler +"]不合法！");
            }
        } else {
            if(!SpringUtil.getApplicationContext().containsBean(jobHandler)){
                throw new ServiceException("目标任务处理器类["+ jobHandler +"]不合法！");
            } else {
                Class<?> type = SpringUtil.getApplicationContext().getType(jobHandler);
                if(!ClassXUtils.isAssignable(IJobHandler.class, type)){
                    throw new ServiceException("目标任务处理器类["+ jobHandler +"]不合法，" +
                            "需要实现com.zxjbyte.yiyi.framework.quartz.core.handler.IJobHandler接口！");
                }
                return ClassUtil.getClassName(type, false);
            }
        }
        return jobHandler;
    }
}
